/**
 * @desc: 退货退款
 * @author: yangshaopeng
 */

import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Modal, message } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import HeaderTab from '@/components/CommonTab';
import CommonBreadcrumb from '@/components/CommonBreadcrumb';
import CommonPagination from '@/components/CommonPagination';
import OrderRefundList from './component/OrderRefundList';
import OrderRefundDetail from './component/OrderRefundDetail';
import FormRender from '@/components/FormRender';
import OperaBtnRender from '@/components/OperaBtnRender';
import { useResize } from '@/hooks/useResize';
import { getFormItem } from './config.js';
import ApplyList from './component/ApplyList/index'
import { cloneDeep, pickBy, identity, isEmpty } from 'lodash';
import { handleExportExcel, getSearchParamsObj } from '@/utils/utils.jsx';
import { getStoreName, getTypeChannel, queryApplyListlData, queryRefundListlData, } from './service';
import moment from 'moment';
import { stringify } from 'qs';

const dateFormat = 'YYYY-MM-DD HH:mm:ss';
const initPagination = {
  current: 1,
  total: 0,
  pageSize: 10,
  showSizeChanger: true,
  showQuickJumper: true,
}

const initQuery1 = {
  // applyTime: [moment().startOf('month'), moment().endOf('day')],
  // finishTime: [moment().startOf('month'), moment().endOf('day')],
}

const tabArr = [//顶部tab信息
  {
    key: '0',
    tab: '售后申请单',
  },
  {
    key: '1',
    tab: '退货商品',
  },
]

const orderRefund = () => {
  const [tabType, setTabType] = useState('0');//0售后申请单 1退货商品
  const [data, setData] = useState([]);
  const [uniqueCode, setUniqueCode] = useState(undefined);//商品唯一码
  const [refundOrderSn, setRefundOrderSn] = useState(undefined);
  const [query, setQuery] = useState({ applyTime1: [moment().startOf('month'), moment().endOf('day')] }); //查询条件
  const [query1, setQuery1] = useState({ ...initQuery1 })
  const [sort, setSort] = useState(1);
  const [filters, setFilters] = useState({});//筛选条件
  const [shopList, setShopList] = useState([]); //下拉店铺列表
  const [warehouseList, setWarehouseList] = useState([]); //下拉渠道列表
  const [pagination, setPagination] = useState({ ...initPagination });
  const [pagination1, setPagination1] = useState();
  const navigate = useNavigate();
  const location = useLocation();
  const stageParams = useRef({});

  //监听变更
  const { el: applyEl, height: applyHeight, onResize: onApplyResize } = useResize();
  const { el: headerEl, height: headerHeight, onResize } = useResize();

  //表单数据
  const applyFormArr = useMemo(() => {
    return getFormItem({
      channelId: warehouseList,
      ecStoreNames: shopList
    }, 'apply');
  }, [shopList, warehouseList])

  const refundFormArr = useMemo(() => {
    return getFormItem({
      channelId: warehouseList,
      ecStoreNames: shopList
    }, 'refund');
  }, [shopList, warehouseList])

  useEffect(() => {
    if(tabType == '0') {
      onApplyResize();
    } else {
      onResize();
    }
  }, [tabType])

  useEffect(() => {
    if (location.pathname == '/trade/refund') {
      const queryObj = getSearchParamsObj(location.search);
      if (queryObj?.orderSn) {
        navigate(location.pathname, { replace: true });
        setQuery1({ orderSns: queryObj.orderSn });
      }
      if (queryObj?.refundOrderSn) {
        navigate(location.pathname, { replace: true });
        setQuery1({ refundOrderSn: queryObj.refundOrderSn });
      }
      if (location.state) {
        const querys = {
          orderSns: location.state.orderSn
        }
        setQuery(querys);
        setTabType('1');
        handleGetOrderRefundList(querys);
      }
    }
  }, [location.pathname])

  useEffect(() => {
    handleGetShopList();
    handleGetTypeChannelList();
  }, [])

  useEffect(() => {
    setPagination1({
      current: 1,
      ...(pagination1 || initPagination)
    })
  }, [sort])

  useEffect(() => {
    if (pagination1 && !location.state) {
      getApplyTableFunc();
    }
  }, [pagination1])

  //判断输入,的次数
  const getCount = (str) => {
    var num = 0; // 这个字符出现的次数
    if (str) {
      var index = str.indexOf(','); // 字符出现的位置
      while (index !== -1) {
        num++; // 每出现一次 次数加一
        index = str.indexOf(',', index + 1); // 从字符串出现的位置的下一位置开始继续查找
      }
    }
    return num;
  };


  //获取申请退货单列表
  const getApplyTableFunc = async () => {
    const params = { ...query1, sort, size: pagination1.pageSize, current: pagination1.current }
    if (params.applyTime1) {
      params.applyTime = moment(params.applyTime1[0]).format(dateFormat);
      params.applyEndTime = moment(params.applyTime1[1]).format(dateFormat);
    }
    if (params.finishTime1) {
      params.finishTime = moment(params.finishTime1[0]).format(dateFormat);
      params.finishEndTime = moment(params.finishTime1[1]).format(dateFormat);
    }
    params.applyTime1 = undefined;
    params.finishTime1 = undefined;
    params.orderSns = query1.orderSns
      ? query1?.orderSns.replace(/，/gi, ',').replace(/\s+/g, '')
      : undefined;
    params.outOrderSns = query1.outOrderSns
      ? query1?.outOrderSns.replace(/，/gi, ',').replace(/\s+/g, '')
      : undefined;
    params.refundStates = query1?.refundStates?.length > 0 ? query1.refundStates.join(',') : undefined;
    params.ecStoreNames = query1?.ecStoreNames?.length > 0 ? query1.ecStoreNames.join(',') : undefined;
    params.storeIds = query1?.storeIds?.join(',') || undefined;
    if (
      getCount(params.orderSns) > 49 ||
      getCount(params.outOrderSns) > 49
    ) {
      return message.warning('最大查询不得超出50条');
    }
    START_LOADING()
    const { data, success } = await queryApplyListlData(params);
    if (success) {
      const { records, total } = data
      pagination1.total = total
      setData(records)
      stageParams.current = { ...params, total, size: undefined, current: undefined };
    } else {
      stageParams.current = { total: 0 };
    }
    END_LOADING()
  }

  //面包屑props
  const breadProps = {
    data: [
      {
        title: '退货商品',
        path: '#/trade/refund',
        onClick() {
          setUniqueCode('');
        }
      },
      {
        title: '退货商品详情'
      }
    ]
  }

  //tab区
  const HeaderTabProps = {
    type: tabType,
    data: tabArr,
    onChange(val) {
      if (val != tabType) {
        setData([])
        setTabType(val);
        if (val == '0') {
          setPagination1({ ...pagination1 })
        } else {
          handleGetOrderRefundList(query);
        }
      }
    }
  }

  //apply表格区
  const ApplyListProps = {
    data,
    headerHeight: applyHeight,
    current: stageParams.current,
    handleJumptDetail(refundOrderSn) {//退货单id
      setTabType('1')
      setQuery({ refundApplyOrder: refundOrderSn })
      handleGetOrderRefundList({ refundApplyOrder: refundOrderSn });
    },
    handleUpdateTable() {
      setPagination1({ ...pagination1 })
    },
    handleSort(val) {
      setSort(val);
    }
  }

  //退货退款列表数据请求
  const handleGetOrderRefundList = async (query = {}, filters = {}, page = undefined, size = undefined) => {
    const obj = { ...query, ...filters }
    const params = cloneDeep(obj);
    if (!isEmpty(query.applyTime)) {//时间
      params.applyTime = moment(query.applyTime[0]).format(dateFormat);
      params.applyTime1 = moment(query.applyTime[1]).format(dateFormat);
    } else {
      params.applyTime = undefined;
      params.applyTime1 = undefined;
    }
    if (params.finishTime) {
      params.finishStartTime = moment(params.finishTime[0]).format(dateFormat);
      params.finishEndTime = moment(params.finishTime[1]).format(dateFormat);
    }
    params.finishTime = undefined;
    const newParams = {
      ...pickBy(params, identity),
      current: page ? page : pagination.current,
      size: size ? size : pagination.pageSize,
      uniqueCodes: query.uniqueCodes
        ? query.uniqueCodes.replace(/，/gi, ',').replace(/\s+/g, '')
        : undefined,
      orderSns: query.orderSns
        ? query.orderSns.replace(/，/gi, ',').replace(/\s+/g, '')
        : undefined,
      outOrderSns: query.outOrderSns
        ? query.outOrderSns.replace(/，/gi, ',').replace(/\s+/g, '')
        : undefined,
      ecStoreNames: query?.ecStoreNames?.length > 0 ? query.ecStoreNames.join(',') : undefined,
      states: query?.states?.length > 0 ? query.states.join(',') : undefined,
    }
    if (
      getCount(newParams.uniqueCodes) > 49 ||
      getCount(newParams.orderSns) > 49 || getCount(newParams.outOrderSns) > 49
    ) {
      return message.warning('最大查询不得超出50条');
    }
    START_LOADING();
    const { data, success } = await queryRefundListlData(newParams)
    if (success) {
      pagination.total = data.total
      setPagination(pagination);
      setData(data.records);
    }
    END_LOADING()
  }



  //列表props
  const CommonProps = {
    data,
    query,
    tabType,
    headerHeight,
    throwParams: (uniqueCode, refundOrderSn) => {
      setUniqueCode(uniqueCode);
      setRefundOrderSn(refundOrderSn);
    },
    handleFiltersChange: (payload) => {
      const params = {
        hasApplyOrder: payload.refundApplyOrder ? payload.refundApplyOrder[0] : undefined,
      }
      setFilters(params);
      handleGetOrderRefundList(query, pickBy(params, identity), 1, undefined);
    }
  }

  //分页
  const pageProps = {
    pagination: tabType == '0' ? pagination1 : pagination,
    style: {
      marginTop: '12px'
    },
    handleChange(page, size) {
      if (tabType == '0') {
        setPagination1({
          ...pagination1,
          current: page,
          pageSize: size
        })
      } else {
        pagination.current = page;
        pagination.pageSize = size;
        setPagination(pagination);
        handleGetOrderRefundList(query, filters, page, size);
      }
    },
  };

  //详情页
  const OrderRefundDetailProps = {
    uniqueCode,
    refundOrderSn
  }

  // 店铺列表
  const handleGetShopList = async () => {
    const res = await getStoreName();
    const { success, data } = res
    if (success) {
      setShopList(data)
    }
  }

  // 渠道列表(自发所有开放渠道)
  const handleGetTypeChannelList = async () => {
    const { success, data } = await getTypeChannel({ isDeleted: 0, type: 2 });
    if (success) {
      setWarehouseList([...data, { id: '0', channelName: '供应商直发渠道' }]);
    }
  }

  const handleClickExportExcel = () => {
    const { total } = pagination;
    if (total) {
      const params = cloneDeep({ ...query, ...filters }), nums = Math.ceil(total / 10000);
      if (!isEmpty(query.applyTime)) {//时间
        params.applyTime = moment(query.applyTime[0]).format(dateFormat);
        params.applyTime1 = moment(query.applyTime[1]).format(dateFormat);
      } else {
        params.applyTime = undefined;
        params.applyTime1 = undefined;
      }
      if (params.finishTime) {
        params.finishStartTime = moment(params.finishTime[0]).format(dateFormat);
        params.finishEndTime = moment(params.finishTime[1]).format(dateFormat);
      }
      params.finishTime = undefined;
      params.states = query?.states?.length > 0 ? query.states.join(',') : undefined,
        params.ecStoreNames = query?.ecStoreNames?.length > 0 ? query.ecStoreNames.join(',') : undefined,
        params.size = 10000;
      for (let i = 1; i <= nums; i++) {
        params.current = i;
        handleExportExcel(
          `/zjf-oms/refunddetail/export?${stringify(params)}`,
          '退货商品.xlsx',
          () => {
            END_LOADING();
          }
        );
      }
    } else {
      Modal.info({ content: '暂无可导出的数据' })
    }
  }
  if (uniqueCode) {
    return (
      <>
        <div style={{ marginBottom: 16 }}><CommonBreadcrumb {...breadProps} /></div>
        <OrderRefundDetail {...OrderRefundDetailProps} />
      </>
    )
  }

  //表单渲染组件
  const ApplyFormRenderProps = {
    query: query1,
    formArr: applyFormArr,
    showExpand: true,
    showKeys: ['refundOrderSn', 'afterSalesType', 'goodsLabel', 'logisticsNo', 'orderSns', 'refundStates'],
    formConfig: {
      name: 'order-refund-manage-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      setQuery1(val)
      setPagination1({
        ...pagination1,
        current: 1
      })
    },
    clickReset() {
      setQuery1({ ...initQuery1 })
      setPagination1({ ...initPagination })
    },
    clickExpand() {
      onApplyResize();
    }
  }

  //表单渲染组件
  const RefundFormRenderProps = {
    query,
    formArr: refundFormArr,
    showExpand: true,
    showKeys: ['refundApplyOrder', 'uniqueCodes', 'orderSns', 'outOrderSns', 'ecStoreNames'],
    formConfig: {
      name: 'order-refund-manage-form',
      style: { marginBottom: '16px' }
    },
    clickSearch(val) {
      pagination.current = 1;
      setPagination(pagination);
      setQuery(val);
      handleGetOrderRefundList(val, filters, undefined, undefined);
    },
    clickReset() {
      pagination.current = 1;
      setPagination(pagination);
      const querys = {
        applyTime: [moment().startOf('month'), moment().endOf('day')],
        uniqueCode: undefined
      }
      setQuery(querys);
      handleGetOrderRefundList(querys, filters, undefined, undefined);
    },
    clickExpand() {
      onResize();
    }
  }

  //操作按钮
  const btnArr = [
    { elType: 'button', text: '表格导出', onClick: handleClickExportExcel }
  ]
  return (
    <>
      <HeaderTab {...HeaderTabProps} />
      <div style={{ display: tabType == '0' ? 'block' : 'none' }}>
        <div ref={applyEl}>
          <FormRender {...ApplyFormRenderProps} />
        </div>
        <div className='global-page-wrap'>
          <ApplyList {...ApplyListProps} />
          <CommonPagination {...pageProps} />
        </div>
      </div>
      <div style={{ display: tabType == '0' ? 'none' : 'block' }}>
        <div ref={headerEl}>
          <FormRender {...RefundFormRenderProps} />
        </div>
        <div className='global-page-wrap'>
          <OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
          <OrderRefundList {...CommonProps} />
          <CommonPagination {...pageProps} />
        </div>
      </div>
    </>
  )
}

export default React.memo(orderRefund, (prevProps, nextProps) => {
  return prevProps.location.state == nextProps.location.state
})
